package ru.nsu.effel.actions;

import java.util.Iterator;
import java.util.List;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.ValidationErrors;
import ru.nsu.effel.persistence.AccountManager;

@UrlBinding("/AuthorizationController.action")
public class AuthorizationControllerActionBean implements ActionBean{
	private ActionBeanContext context;
	private String login;
	private String password;

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public ActionBeanContext getContext() {
		return context;
	}

	public void setContext(ActionBeanContext context) {
		this.context = context;
	}
	
	@DefaultHandler
	public Resolution logIn() {
		ValidationErrors verrors = new ValidationErrors();
		if ((null == login) || (null == password)) {
			verrors.add("loginpassword", new SimpleError("Enter login and password"));
			getContext().setValidationErrors(verrors);
			return getContext().getSourcePageResolution();
		}
		List credentials = AccountManager.getInstance().getCredentials();
		for(Iterator iter = credentials.iterator(); iter.hasNext(); ) {
			Object[] response = (Object[])iter.next();
			if ((login.equals((String)response[1])) && (password.equals((String)response[2]))) {
				getContext().getRequest().getSession().setAttribute("accountId", response[0]);
				String str = (String)response[3];
				if (str.equals("Fitter")) return new RedirectResolution("/FitterProfile.jsp");
				if (str.equals("Manager") || str.equals("Director")) return new RedirectResolution("/ManagerProfile.jsp");
				if (str.equals("Client")) return new RedirectResolution("/ClientProfile.jsp");
			}
		}
		verrors.add("incorrect", new SimpleError("Incorrect login or password"));
		getContext().setValidationErrors(verrors);
		return getContext().getSourcePageResolution();
	}
	
	public Resolution logout() {
		getContext().getRequest().getSession().removeAttribute("accountId");
		return new RedirectResolution("/index.jsp");
	}
}
